package system

import (
	"context"
	"fmt"
	"private-domain-overseas-service/app/business/api/internal/repository/system"
	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent/hzsystemconfig"
	"private-domain-overseas-service/tools/ent/predicate"

	"github.com/zeromicro/go-zero/core/logx"
)

type SystemConfigLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewSystemConfigLogic - 系统配置通用查询
func NewSystemConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemConfigLogic {
	return &SystemConfigLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SystemConfigLogic) SystemConfig(req *types.SystemConfigRequest) (resp *types.SystemConfigResponse, err error) {
	// 创建实例
	configDao := system.NewSystemConfigDao(l.ctx, l.svcCtx)

	// 定义返回值value
	var systemValue string

	// redis中获取所查系统配置
	systemValue, err = l.svcCtx.BizRedis.Hget(constant.HzAdminSystemConfigKey, req.SystemKey)
	if err != nil {
		l.Errorf("redis中获取所查系统配置失败：配置key:%s,错误:%v", req.SystemKey, err.Error())
	}

	// 如果未查到则从mysql中查一遍
	if systemValue == "" {
		systemConfigConditions := make([]predicate.HzSystemConfig, 0)
		systemConfigConditions = append(systemConfigConditions, hzsystemconfig.SystemKeyEQ(req.SystemKey))
		systemConfigConditions = append(systemConfigConditions, hzsystemconfig.DeleteAtIsNil())
		systemConfig, errFirst := configDao.SystemConfigConditionsFirst(systemConfigConditions)
		if errFirst != nil {
			return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("mysql中获取所查系统配置失败：配置key:%s,错误:%v", req.SystemKey, errFirst.Error()))
		}
		systemValue = systemConfig.SystemValue
	}

	// 返回数据
	return &types.SystemConfigResponse{
		SystemValue: systemValue,
	}, nil

}
